package com.atguigu.gulimall.ware.rabbitListener;

import com.atguigu.common.to.LockStockTo;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.gulimall.ware.cons.OrderRabbitConst;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@Service
@RabbitListener(queues = OrderRabbitConst.NORMAL_QUEUE)
public class WareRelease {

    @Autowired
    WareSkuService wareSkuService;

    /**
     * @param lockStockTo 远程服务传输的对象
     * @param channel     管道
     * @param message     消息
     */
    @RabbitHandler
    public void releaseStock(LockStockTo lockStockTo, Channel channel, Message message) throws IOException {
        log.info("即将释放库存：" + lockStockTo.getOrderSn());
        try {
            wareSkuService.releaseStock(lockStockTo);
            //无异常，手动消息确认,将消息进行消费
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("库存释放完成，消息消费完毕");
//            System.out.println("消息消费完毕");
        } catch (Exception exception) {
            //调用释放库存的方法出现任何异常都不消费消息，让消息重新回到队列中
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
//            System.out.println("消息未被成功消费，重新进入队列等待消费。。。");
            log.info("库存释放失败，消息重新入队");
        }
    }

    @RabbitHandler
    public void directReleaseStock(OrderTo order, Message message, Channel channel) throws IOException {
        log.info("订单服务主动触发的释放库存：" + order);
        try {
            wareSkuService.releaseStock(order);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("订单服务主动触发的释放库存操作成功，消息成功消费");
        } catch (Exception exception) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            log.info("订单服务主动触发的释放库存操作失败，消息重新入队");
        }
    }


}
